<?php
/*
*   @package httpRequest class
*   @author  Sebastian Azagra <varseb@gmail.com>
*   @license MIT License
*/

final class httpRequest {

    public static function Post( $host ){
        return new self('POST', $host);
    }

    public static function Get( $host ){
        return new self('GET', $host);
    }

    private $method   = null;
    private $host     = null;
    private $path     = null;
    private $data     = array();
    private $headers  = array();

    public $response        = null;
    public $responseHeaders = array();

    public function __construct( $method, $host ){

        $this->method = $method;

        if ( preg_match('@^([\w-\.]+)(/.+)?$@', $host, $match ) ){
            $this->host = strtolower($match[1]);
            $this->path = isset($match[2]) ? $match[2] : '/';
        }
    }

    public function set( $name, $value = null ){
        if ( is_array($name) ){
            foreach ( $name as $key => $value )
                $this->data[$key] = $value;
        }
        else
            $this->data[$name] = $value;

        return $this;
    }

    public function setHeader( $name, $value = null ){
        if ( is_array($name) ){
            foreach ( $name as $key => $value )
                $this->setHeader($key, $value);
        }
        elseif ( is_array($value) ){
            foreach ( $value as $every )
                $this->setHeader($name, $every);
        }
        else {
            if ( isset($this->headers[$name]) ){
                if ( is_array($this->headers[$name]) )
                    $this->headers[$name][] = $value;
                else
                    $this->headers[$name] = array($this->headers[$name], $value);
            }
            else
                $this->headers[$name] = $value;
        }

        return $this;
    }

    public function send(){

        $headers = array(
            'Host'       => $this->host,
            'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201',
          # 'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
            'Accept'     => 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain;'
        );

        $headers = array_merge($headers, $this->headers);

        $data = $this->makeQueryString();

        if ( $this->method == 'POST' ){
            $headers['Content-Type']   = 'application/x-www-form-urlencoded';
            $headers['Content-Length'] = strlen($data);
            $path = $this->path;
        }
        else
            $path = $this->path . $data;

        $send = "$this->method $path HTTP/1.1\r\n";

        foreach ( $headers as $name => $value ){
            if ( is_array($value) )
                $send .= "$name: " . implode('; ', $value) . "\r\n";
            else
                $send .= "$name: $value\r\n";
        }

        $send .= "Connection: close\r\n\r\n";

        if ( $this->method == 'POST' )
            $send .= $data;

        $fp = fsockopen($this->host, 80, $errno, $errstr, 30);

        if ( $fp ){

            fwrite($fp, $send);

            $isHeader   = true;
            $resHeaders = '';

            while ( !feof($fp) ){
                $buffer = fgets($fp, 128);

                if ( $isHeader )
                    $resHeaders .= $buffer;
                else
                    $this->response .= $buffer;

                if ( $buffer == "\r\n" )
                    $isHeader = false;
            }

            fclose($fp);

            $this->responseHeaders = $this->getResponseHeaders($resHeaders);
        }

        return $this;
    }

    public function getHeader( $name ){
        return $this->responseHeaders[$name];
    }

    private function makeQueryString(){

        $i    = 0;
        $data = '';
        foreach ( $this->data as $name => $value ){
            $q = ( $i == 0 && $this->method == 'GET' ) ? '?' : ( $i > 0 ? '&' : '' );
            $data .= sprintf('%s%s=%s', $q, $name, $value);
            $i++;
        }

        return $data;
    }

    private function getResponseHeaders( $strHeaders ){

        $headers = array();
        $matches = array();

        if ( preg_match_all('@([\w-]+):\s*(.+)@', $strHeaders, $matches, PREG_SET_ORDER) ){

            foreach ( $matches as $match ){
                $name  = trim($match[1]);
                $value = trim($match[2]);

                if ( isset( $headers[$name] ) ){
                    if ( is_array($headers[$name]) )
                        $headers[$name][] = $value;
                    else
                        $headers[$name] = array($headers[$name], $value);
                }
                else
                    $headers[$name] = $value;
            }
        }

        return $headers;
    }
}

?>